package cn.tnar.parkservice.task;

import cn.tnar.parkservice.config.Constant;
import cn.tnar.parkservice.exception.CustomException;
import cn.tnar.parkservice.model.entity.*;
import cn.tnar.parkservice.model.request.TParkGroupMemberinfoRequest;
import cn.tnar.parkservice.service.*;
import cn.tnar.parkservice.util.DateUtils;
import cn.tnar.parkservice.util.common.ResultJson;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author zzb
 * @ClassName:
 * @Description:
 * @date 2019年09月12日 11:10:56
 */
@Component
@Slf4j
public class WhiteExpireTask {

    @Autowired
    ITParkMemberGroupService itParkMemberGroupService;
    @Autowired
    ITParkMemberGroupRelationService itParkMemberGroupRelationService;
    @Autowired
    ITParkGroupMemberinfoService itParkGroupMemberinfoService;
    @Autowired
    ITParkGroupSeatinfoService itParkGroupSeatinfoService;
    @Autowired
    ITParkGroupOperateLogService itParkGroupOperateLogService;
    @Autowired
    ITParkGroupCarinfoService itParkGroupCarinfoService;
    @Autowired
    ITDictionaryService itDictionaryService;

    //白名单置过期
    @Scheduled(cron = "0 10 0 * * ?")
    public void whiteExpireTask() {
        //白名单将过期的carstate置为2
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        Long now = Long.valueOf(format.format(new Date()));
        List<String> allWhiteId = itParkMemberGroupService.getAllWhiteId();
        QueryWrapper<TParkMemberGroupRelation> qw = new QueryWrapper<>();
        qw.in("group_id", String.join(",", allWhiteId));
        List<TParkMemberGroupRelation> list = itParkMemberGroupRelationService.list(qw);
        for (int i = 0; i < list.size(); i++) {
            TParkGroupMemberinfo byId = itParkGroupMemberinfoService.getById(list.get(i).getMemberId());
            if (now.longValue() > byId.getEndDate().longValue() && byId.getCarState() == 1 && byId.getDelflag() == 1) {
                TParkGroupMemberinfo info = new TParkGroupMemberinfo();
                info.setId(byId.getId());
                info.setCarState(2);
                itParkGroupMemberinfoService.updateById(info);
            }
        }
    }

    //白名单/新版会员自动启用
    @Scheduled(cron = "0 0 0 * * ?")
    public void wemberStartTask() {
        QueryWrapper<TParkGroupMemberinfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("car_state", 3);//只有白名单暂停状态为3 会员暂停状态在车位里面
        queryWrapper.eq("delflag", 1);
        List<TParkGroupMemberinfo> list = itParkGroupMemberinfoService.list(queryWrapper);
        for (int i = 0; i < list.size(); i++) {
            Long memberinfoId = list.get(i).getId();
//            QueryWrapper<TParkGroupSeatinfo> qw = new QueryWrapper<>();
//            qw.eq("member_id", memberinfoId);
//            List<TParkGroupSeatinfo> seatinfoList = itParkGroupSeatinfoService.list(qw);
//            if (seatinfoList.size() == 0) {
//                //白名单无seatinfo  再调用启用白名单
            checkStopDate(1, null, memberinfoId);
//            }
        }
        //新版会员
        QueryWrapper<TParkGroupSeatinfo> seatinfoQueryWrapper = new QueryWrapper<>();
        seatinfoQueryWrapper.eq("car_state", 3);
        List<TParkGroupSeatinfo> seatinfoLists = itParkGroupSeatinfoService.list(seatinfoQueryWrapper);

        for (int j = 0; j < seatinfoLists.size(); j++) {
            checkStopDate(2, seatinfoLists.get(j).getId(), seatinfoLists.get(j).getGroupId());
        }
    }

    private void checkStopDate(int type, Long seatinfoId, Long memberinfoId) {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        Long now = Long.valueOf(format.format(new Date()));
        QueryWrapper<TParkGroupOperateLog> qw = new QueryWrapper<>();
        if (type == 1) {
            qw.eq("group_id", memberinfoId);
        } else {
            qw.eq("seat_id", seatinfoId);
        }
        qw.eq("operate_type", 7);
        qw.orderByDesc("operate_time");
        qw.last("limit 1");
        TParkGroupOperateLog operateLog = itParkGroupOperateLogService.getOne(qw);
        Integer operateDay = operateLog.getOperateDay();
        String operateTime = operateLog.getOperateTime().toString().substring(0, 8);
        try {
            //判断是否是需要启用日期
            if (DateUtils.differentDaysByMillisecond(format.parse(operateTime), format.parse(String.valueOf(now))) == operateDay.intValue()) {
                if (type == 1) {
                    TParkGroupMemberinfoRequest request = new TParkGroupMemberinfoRequest();
                    request.setGroupMemberinfoId(memberinfoId);
                    ResultJson whiteStart = itParkGroupMemberinfoService.start(JSON.toJSONString(request));
                    log.info("白名单定时启用:" + whiteStart);
                } else {
                    Map<String, Object> map = new HashMap<>();
                    map.put("group_id", memberinfoId.toString());
                    map.put("seat_id", seatinfoId.toString());
                    map.put("operator", "0");
                    ResultJson memberStart = itParkGroupMemberinfoService.startMemberSeat(JSON.toJSONString(map));
                    log.info("新版会员定时启用:" + memberStart);
                }
            }
        } catch (ParseException e) {
            log.error(Constant.ERROR_MSG_DATE, e);
            throw new CustomException(Constant.ERROR_MSG_DATE);
        }
    }

    //新版预会员过期删除
    @Scheduled(cron = "0 0 0 * * ?")
    public void deleteTask() {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        Long now = Long.valueOf(format.format(new Date()));
        QueryWrapper<TParkGroupMemberinfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("member_type", 2);//只有白名单暂停状态为3 会员暂停状态在车位里面
        queryWrapper.lt("expire_time", now);
        List<TParkGroupMemberinfo> list = itParkGroupMemberinfoService.list(queryWrapper);
        TParkGroupMemberinfo tParkGroupMemberinfo = new TParkGroupMemberinfo().setDelflag(2);
        itParkGroupMemberinfoService.update(tParkGroupMemberinfo, queryWrapper);
        for (int i = 0; i < list.size(); i++) {
            Long memberinfoId = list.get(i).getId();
            itParkMemberGroupRelationService.remove(new QueryWrapper<TParkMemberGroupRelation>().eq("member_id", memberinfoId));
            itParkGroupCarinfoService.update(new TParkGroupCarinfo().setDelflag(2), new QueryWrapper<TParkGroupCarinfo>().eq("group_id", memberinfoId));
            itParkGroupSeatinfoService.remove(new QueryWrapper<TParkGroupSeatinfo>().eq("member_id", memberinfoId));
        }
    }

   /* //满免金额每月最后一天清除
    @Scheduled(cron = "50 59 23 28-31 * ?")
    public void clearFreeAmtTask() {
        log.info("清理满免额度定时任务开始");
        Calendar c = Calendar.getInstance();
        if (c.get(Calendar.DATE) != c.getActualMaximum(Calendar.DATE)) {
            //不是最后一天
            log.info("不是最后一天------定时任务结束");
            return;
        } else {
            UpdateWrapper<TParkMemberGroup> queryWrapper = new UpdateWrapper<>();
            queryWrapper.set("total_fullFree_amt", null);
            boolean update = itParkMemberGroupService.update(queryWrapper);

            if(update){
                log.info("清除分组表成功");
            }else{
                log.info("清除分组表失败------定时任务结束");
                return;
            }

            UpdateWrapper<TParkGroupMemberinfo> memberinfoUpdateWrapper = new UpdateWrapper<>();
            memberinfoUpdateWrapper.set("accumulate_amt", null);
            boolean memberUpdate = itParkGroupMemberinfoService.update(memberinfoUpdateWrapper);
            if(memberUpdate){
                log.info("清除会员表成功------定时任务结束");
            }else {
                log.info("清除分组表失败------定时任务结束");
                return;
            }

        }
    }*/

    //满免金额清除 字典表加时间  每小时执行一次
    @Scheduled(cron = "0 0 * * * ?")
    public void clearFreeAmtTask() {
        log.info("清理满免额度定时任务------开始");
        QueryWrapper<TParkMemberGroup> tParkMemberGroupQueryWrapper = new QueryWrapper<>();
        tParkMemberGroupQueryWrapper.eq("type", 1);
        tParkMemberGroupQueryWrapper.eq("classify", 5);
        tParkMemberGroupQueryWrapper.eq("del_flag", 0);
        tParkMemberGroupQueryWrapper.eq("is_fullFree", 1);
        List<TParkMemberGroup> groupList = itParkMemberGroupService.list(tParkMemberGroupQueryWrapper);

        int currentMonthLastDay = getCurrentMonthLastDay();//当前月有多少天
        String ddString = DateUtils.getNowString("dd");
        String hourString = DateUtils.getNowString("HH");

        for (int i = 0; i < groupList.size(); i++) {
            String time = groupList.get(i).getClearAmtDate();
            String day = time.substring(0, 2);
            String hour = time.substring(2, 4);

            //如果设置的日大于当月总天数时，在当月最后一天执行
            if (Integer.valueOf(day) > currentMonthLastDay) {
                Calendar c = Calendar.getInstance();
                if (c.get(Calendar.DATE) == c.getActualMaximum(Calendar.DATE) && hour.equals(hourString)) {
                    Boolean aBoolean = clearFreeAmt(groupList.get(i).getId());
                    if(aBoolean){
                        continue;
                    }else {
                        return;
                    }

                }
            } else {
                if (day.equals(ddString) && hour.equals(hourString)) {
                    Boolean aBoolean = clearFreeAmt(groupList.get(i).getId());
                    if(aBoolean){
                        continue;
                    }else {
                        return;
                    }

                }
            }

        }
        log.info("清理满免额度定时任务------结束");

    }

    public Boolean clearFreeAmt(Long groupId) {
        UpdateWrapper<TParkMemberGroup> queryWrapper = new UpdateWrapper<>();
        queryWrapper.set("total_fullFree_amt", null);
        queryWrapper.eq("id", groupId);
        boolean update = itParkMemberGroupService.update(queryWrapper);

        if (update) {
            log.info("清除" + groupId + "分组表成功");
        } else {
            log.info("清除" + groupId + "分组表失败------定时任务结束");
            return false;
        }


        QueryWrapper<TParkMemberGroupRelation> relationQueryWrapper = new QueryWrapper<>();
        relationQueryWrapper.eq("group_id", groupId);
        List<TParkMemberGroupRelation> list = itParkMemberGroupRelationService.list(relationQueryWrapper);

        for (int i = 0; i < list.size(); i++) {
            UpdateWrapper<TParkGroupMemberinfo> memberinfoUpdateWrapper = new UpdateWrapper<>();
            memberinfoUpdateWrapper.set("accumulate_amt", null);
            memberinfoUpdateWrapper.eq("id", list.get(i).getMemberId());
            boolean memberUpdate = itParkGroupMemberinfoService.update(memberinfoUpdateWrapper);
            if (!memberUpdate) {
                log.info("清除分组表会员id:" + list.get(i).getMemberId() + "失败");
            }

        }
        log.info("清除会员表" + groupId + "卡组下会员成功");
        return true;
    }


    public static int getCurrentMonthLastDay() {
        Calendar a = Calendar.getInstance();
        a.set(Calendar.DATE, 1);//把日期设置为当月第一天
        a.roll(Calendar.DATE, -1);//日期回滚一天，也就是最后一天
        int maxDate = a.get(Calendar.DATE);
        return maxDate;
    }

}
